﻿using Microsoft.Extensions.Logging;
using Service.Framework.Utils.Extension;
using SqlSugar;
using System.Collections.Concurrent;
using System.Reflection;

namespace Service.Core.Repository.UnitOfWorks
{
    public class UnitOfWorkManage(ISqlSugarClient sqlSugarClient, ILogger<UnitOfWorkManage> logger) : IUnitOfWorkManage
    {
        private readonly ILogger<UnitOfWorkManage> _logger = logger;
        private readonly ISqlSugarClient _sqlSugarClient = sqlSugarClient;

        private int _tranCount { get; set; } = 0;
        public int TranCount => _tranCount;
        public readonly ConcurrentStack<string> TranStack = new();

        private bool _transactionActive;

        /// <summary>
        /// 获取DB，保证唯一性
        /// </summary>
        /// <returns></returns>
        public SqlSugarClient GetDbClient()
        {
            // 必须要as，后边会用到切换数据库操作
            return (SqlSugarClient)_sqlSugarClient;
        }

        public void BeginTran()
        {
            lock (this)
            {
                if (!_transactionActive)
                {
                    _transactionActive = true;
                    _tranCount++;
                    GetDbClient().BeginTran();
                }
            }
        }

        public void CommitTran()
        {
            lock (this)
            {
                _tranCount--;
                if (_tranCount == 0 && _transactionActive)
                {
                    try
                    {
                        _transactionActive = false;
                        GetDbClient().CommitTran();
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex.Message);
                        GetDbClient().RollbackTran();
                    }
                }
            }
        }

   

        public void RollbackTran()
        {
            lock (this)
            {
                if (_transactionActive)
                {
                    _transactionActive = false;
                    _tranCount--;
                    GetDbClient().RollbackTran();
                }
            }
        }
        public bool HasActiveTransaction()
        {
            return _transactionActive;
        }

       
    }
}